import axios from "axios";

const originAxios = axios.create();

function addAuthorization(config) {
  let headers = config.headers;
  let token = sessionStorage.getItem("token");
  if (token) {
    headers["Authorization"] = "Bearer " + token;
  } else {
    config.data = config.data;
  }
}

// axios默认配置
originAxios.defaults.timeout = 10000; // 超时时间
originAxios.defaults.baseURL = process.env.VUE_APP_URL;

// http request 拦截器
originAxios.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers["Access-Control-Allow-Origin"] = "*";
    config.headers["Access-Control-Allow-Header"] = "Content-Type,*";
    addAuthorization(config);
    return config;
  },
  (error) => {
    return Promise.reject(error.response);
  }
);

async function getGitRevision({ module }) {
  const url = `/${module}/actuator/info`;
  return await originAxios.get(url);
}

const MUTATION_TYPES = {
  GIT_REVISION: "GIT_REVISION"
};

const state = {
  gitRevisions: {}
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.GIT_REVISION](state, { module, gitRevision }) {
    let tempGitRevisions = { ...state.gitRevisions };
    tempGitRevisions[module] = gitRevision;
    state.gitRevisions = tempGitRevisions;
  }
};

const actions = {
  async loadGitRevisions({ commit }, module) {
    if (!module) {
      return state.gitRevisions;
    }
    let response = await getGitRevision({ module });
    console.log("Git revision:", response.data.git);
    commit(MUTATION_TYPES.GIT_REVISION, {
      module,
      gitRevision: response.data.git
    });
    return state.gitRevisions;
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
